<?php 
try {
	include_once('db/constants.php');
	include_once('db/get_contents_db.php');
	include_once('db/get_categories_db.php');
	include_once('db/general_functions_db.php');
	include_once('db/error_log_db.php');
	include_once('db/update_user_db.php');
	include_once('facebook_login.php');

	if (isset($user_profile)) {

		$current_file = "Contents";
		include_once("users_flow_logger.php");

		updateUser($user_profile['id'], $user_profile['first_name'], $user_profile['last_name'], $_SERVER['HTTP_USER_AGENT']);

	}

	function getBests() {
		if ( isset($_REQUEST['get_bests']) ) { 
			if ($_REQUEST['get_bests'] == "1") {
				return 1;	
			}
			return 0;
		}

		return 1;
	}

	function replaceBreaks($str) {
		return str_replace("<br />", "  ", $str);
	}

	function setStandarLogo() {
		global 	$urlImage;
		global $imageWidth;
		global $imageHeight;
		
		$urlImage = SERVER_WEB.'logo/logo.png';
		$imageWidth = 599;
		$imageHeight = 314;
	}


	$category_id_logMsg = isset($_REQUEST['category_id']) ? $_REQUEST['category_id'] : "best";
	logMsg($user_profile['id'], "Contents.php. Category=".$category_id_logMsg);

	updateUser($user_profile['id'], $user_profile['first_name'], $user_profile['last_name'], $_SERVER['HTTP_USER_AGENT']);

	$user_id = isset($user_profile['id']) ? $user_profile['id'] : -1;

	$urlImage = '';
	$imageWidth = '';
	$imageHeight = '';


	// Order: content_id, category_id
	// Seting info for page metadata
	$content_id_metadata = isset($_REQUEST['content_id']) ? "content_id=".$_REQUEST['content_id'] : "";
	$category_id_metadata = isset($_REQUEST['category_id']) ? "category_id=".$_REQUEST['category_id'] : "";

	// Url metadata
	if ($content_id_metadata == "" && $category_id_metadata != "") {
		$category_id_metadata = "?".$category_id_metadata;
	} else if ($content_id_metadata != "" && $category_id_metadata == "") {
		$content_id_metadata = "?".$content_id_metadata;
	} else if ($content_id_metadata != "" && $category_id_metadata == "") {
		$content_id_metadata = "?".$content_id_metadata;
		$category_id_metadata = "&".$category_id_metadata;
	}

	$url_description = "";
	if ( isset($_REQUEST['content_id']) ) {
		$content_from_url_json = get_one_content($_REQUEST['content_id'], $user_id);
		$content_from_url = json_decode($content_from_url_json);
		$url_description = $content_from_url->content;
	}

	setStandarLogo();
	// Load correct category and image
	if ( isset($_REQUEST['category_id']) && isset($_REQUEST['content_id']) == false ) {
		$category_json = get_one_category($_REQUEST['category_id'], $user_id);
	} else if ( isset($_REQUEST['category_id']) == false && isset($_REQUEST['content_id']) == false ) {
		$category_json = "";
	} else {
		$category_json = get_one_category($content_from_url->category_id, $user_id);
		$urlImage = SERVER_WEB.IMAGES_PATH.$_REQUEST['content_id'].".png";
		$imageWidth = 1200;
		$imageHeight = 630;
	}
	
	$category = ($category_json != "") ? json_decode($category_json) : "";

	// Description metadata
	if ( isset($_REQUEST['content_id']) == false && isset($_REQUEST['category_id']) ) {
		$url_description = $category->name;
	}

	$url_description = ($url_description != "") ? $url_description : DEFAULT_SITE_DESCRIPTION;
	$url_description = stripslashes($url_description);
	
	// Load image
	if ( isset($_REQUEST['content_id'])) {
		$fileName = IMAGES_PATH.$_REQUEST['content_id'].'.png';
		if (!file_exists($fileName)) {
			include_once("./imageGenerator/generate.php");

			generateImage(stripslashes($content_from_url->content), stripslashes($category->name), $fileName);
		}
	}

} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta property="fb:app_id" content="<?php echo APP_ID;?>" /> 
	<meta property="og:url" content="<?php echo APP_CANVAS.CONTENTS_URL.$content_id_metadata.$category_id_metadata;?>" /> 
	<meta property="og:title" content="<?php echo HTML_TITLE;?>" />
	<meta property="og:description" content="<?php echo replaceBreaks($url_description);?>" /> 
	<meta property="og:site_name" content="<?php echo SITE_NAME;?>" />
	<meta property="og:locale" content="es_LA" /> 
	<meta property="og:image" content="<?php echo $urlImage.'?v='.rand(); ?>" /> 
	<meta property="og:image:width" content="<?php echo $imageWidth; ?>">
	<meta property="og:image:height" content="<?php echo $imageHeight; ?>">

	<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
	<title><?php echo HTML_TITLE;?></title>
	<link rel="stylesheet" href="css/style.css" type="text/css" media="all" />
	<!--[if lte IE 6]><link rel="stylesheet" href="css/ie6.css" type="text/css" media="all" /><![endif]-->
	
	<script src="js/jquery-1.4.1.min.js" type="text/javascript"></script>
	<script src="js/spin.js" type="text/javascript"></script>
	<script src="js/wrap_content.js?<?php echo REVISION;?>" type="text/javascript"></script>
	<script src="js/general_slider_functions.js?<?php echo REVISION;?>" type="text/javascript"></script>

	<script>
		<?php 
			if ( isset($_REQUEST['content_id']) ) { 
				echo "currentContent = JSON.parse(\"".addslashes($content_from_url_json)."\");";
			}

			$category_id = ($category != "" ) ? $category->category_id : -1;

			if ($category != "")
				echo "currentCategory = JSON.parse(\"".addslashes($category_json)."\");";
			else
				echo "currentCategory = null;";
		?>

		APP_CANVAS = '<?php echo APP_CANVAS; ?>';
		var CONTENTS_URL = '<?php echo CONTENTS_URL; ?>';
		LOAD_AMOUNT = '<?php echo LOAD_AMOUNT; ?>';
		contents = JSON.parse( '<?php echo get_bests_lasts_content_db(INITIAL_LOAD_AMOUNT, -1, $user_profile['id'], getBests(), $category_id); ?>' );
		allContentsLoaded = (contents.length < <?php echo INITIAL_LOAD_AMOUNT; ?>) ? true : false;
		getContentsUrlCall = "db/get_contents_db.php?limit=" + LOAD_AMOUNT + "&user_id=<?php echo $user_profile['id'] ?>"
		getContentsUrlCall = (currentCategory != null && currentContent == null) ? getContentsUrlCall + "&category_id=" + currentCategory.category_id : getContentsUrlCall;
		specialLastContent = true;
		bestById = true;
		var showingComments = false;
		var showingEmptyContents = true;

		// Header extra logger
		var buttonsHrefs = null;
		var buttonsToUpdate = new Array('header-first', 'header-second', 'header-categories', 'see-content-0', 'see-content-1', 'see-content-2', 'see-all-author-content-0', 'see-all-author-content-1', 'see-all-author-content-2', 'see-best-authors', 'see-best-contents');

		function updateHeaderHrefs() {
			if (buttonsHrefs == null) {
				buttonsHrefs = new Array();

				for (var i = 0; i < buttonsToUpdate.length; i++) {
					if (document.getElementById(buttonsToUpdate[i]))
						buttonsHrefs[i] = document.getElementById(buttonsToUpdate[i]).href;
				}
			}

			for (var i = 0; i < buttonsToUpdate.length; i++) {
				if (document.getElementById(buttonsToUpdate[i]))
					document.getElementById(buttonsToUpdate[i]).href = buttonsHrefs[i] + "&log_extra=" + generateExtraLog();
			}	
		}


		function updateLastIdContent() {
			if (contents.length > 0)
				lastIdContent = contents[ contents.length - 1 ].content_id;
		}

		function updateLastPointsContent() {
			if (contents.length > 0)
				lastPointsContent = contents[ contents.length - 1 ].points;
		}

		function showContent(content) {
			showContentsSlider();
			document.title = content.content;

			document.getElementById('content-text').innerHTML = removeSlashes(content.content);
			document.getElementById('content-text').style.fontSize = <?php echo CONTENT_DEFAULT_FONT_SIZE; ?> + "px";
			document.getElementById('content-author-text').innerHTML = content.first_name + ' ' + content.last_name;

			resizeContentDisplay();
			
			if (content.calification == 1) {
				document.getElementById('like-button').className  = "button-content-like-active";
				document.getElementById('dislike-button').className  = "button-content-dislike";
			} else if (content.calification == -1) {
				document.getElementById('like-button').className  = "button-content-like";
				document.getElementById('dislike-button').className  = "button-content-dislike-active";	
			} else {
				document.getElementById('like-button').className  = "button-content-like";
				document.getElementById('dislike-button').className  = "button-content-dislike";
			}
			
			document.getElementById("content-like").setAttribute("data-href", APP_CANVAS + CONTENTS_URL + "?content_id=" + content.content_id);

			document.getElementById("category-name-upper-slider").innerHTML = content.category_name;
			document.getElementById("category-name-upper-slider").href = "<?php echo CONTENTS_URL;?>?category_id=" + content.category_id;

			// Check if FB is loaded
			if ("FB" in window)
				FB.XFBML.parse(document.getElementById('content-like-td'));
		}

		function showLastContent() {
			showEmptyContents();
			var contentElement = document.getElementById('content-text');
			var noMoreBestContent = (<?php echo ($category != "") ? "true" : "false";?>) ? "<?php echo NO_MORE_BEST_CONTENT;?>" : "<?php echo NO_MORE_BEST_CONTENT_NO_CATEGORY;?>";
			var noMoreContent = (<?php echo ($category != "") ? "true" : "false";?>) ? "<?php echo NO_MORE_CONTENT;?>" : "<?php echo NO_MORE_CONTENT_NO_CATEGORY;?>";

			contentElement.style.overflowY = "visible";

			if (showingBestContents == '1')
				contentElement.innerHTML = noMoreBestContent + '<img src="css/images/LastButtonClickMessage.png" style="margin-left: 150px; margin-top: 20px;" />';
			else
				contentElement.innerHTML = noMoreContent + '<img src="css/images/CategoryButtonClickMessage.png" style="margin-left: 150px; margin-top: 20px;" />';

			document.getElementById("category-name-upper-slider").innerHTML = "<br />";
			document.getElementById("category-name-upper-slider").href = "#";

			document.getElementById("prev-button").style.display = '';
			document.getElementById("next-button").style.display = 'none';
			
			document.getElementById('content-text').style.fontSize = "15px";
			showingLastContent = true;
		}

		function showEmptyContents() {
			document.getElementById('content-text').style.overflowY = "visible";
			document.getElementById('content-text').innerHTML = "<?php echo EMPTY_CONTENTS;?>";
			document.getElementById('bottom-bar-tr').style.height = "";
			document.getElementById('like-button').style.visibility = "hidden";
			document.getElementById('dislike-button').style.visibility = "hidden";
			document.getElementById('comment-button').style.visibility = "hidden";
			document.getElementById('content-author-text').style.visibility = "hidden";
			document.getElementById('share-button').style.visibility = "hidden";
			document.getElementById('content-like-td').innerHTML = "";

			document.getElementById("category-name-upper-slider").innerHTML = "<br />";
			document.getElementById("category-name-upper-slider").href = "#";

			showingEmptyContents = true;
		}

		function showContentsSlider() {
			if (showingEmptyContents == false)
				return;

			document.getElementById('content-text').style.overflowY = "auto";
			document.getElementById('bottom-bar-tr').style.height = "22%";
			document.getElementById('like-button').style.visibility = "visible";
			document.getElementById('dislike-button').style.visibility = "visible";
			document.getElementById('comment-button').style.visibility = "visible";
			document.getElementById('content-author-text').style.visibility = "visible";
			document.getElementById('share-button').style.visibility = "visible";
			document.getElementById('content-like-td').innerHTML = '<div id="content-like" style="margin-top: 6px;" data-href="<?php echo APP_CANVAS; ?>" class="fb-like" data-width="150" data-layout="button_count" data-send="true" share="false" data-show-faces="false"></div>';

			showingEmptyContents = false;
		}

		function showFakeArrows() {
			document.getElementById('prev-button').onclick = function() { fakeArrowFunction() };
			document.getElementById('next-button').onclick = function() { fakeArrowFunction() };
			showMoveArrows();
		}

		function showTrueArrows() {
			document.getElementById('prev-button').onclick = function() {  moveLeft() };
			document.getElementById('next-button').onclick = function() {  moveRight() };
		}

		function fakeArrowFunction() {
			showTrueArrows();
			showBestsContents();
		}

		function showLoadingContent() {
			showEmptyContents();
			document.getElementById('content-text').innerHTML = '<img src="logo/LoadingLogo.png" style="margin-left: 95px; margin-top: -10px;" />';
		}

		function resizeContentDisplay() {
			var contentObject = document.getElementById('content-text');
			contentObject.style.fontSize = "<?php echo CONTENT_DEFAULT_FONT_SIZE;?>" + "px";
			var content_max_heigth = <?php echo CONTENT_MAX_HEIGTH; ?>;
			var fontSize = parseInt(contentObject.style.fontSize.substr(0, 2));
			
			while (fontSize > <?php echo CONTENT_MIN_FONT_SIZE; ?>) {
				fontSize =  parseInt(contentObject.style.fontSize.substr(0, 2));
				
				if (contentObject.offsetHeight > content_max_heigth) {
					contentObject.style.fontSize = (fontSize - 1) + "px";
				} else {
					break;
				}
			}
			
			if (contentObject.offsetHeight > content_max_heigth) {
				contentObject.style.height = <?php echo CONTENT_MAX_HEIGTH; ?> + "px";
			}
		}
		
		// rating = 1 for like
		// rating = -1 for dislike
		function rateContent(rating) {
			spinner.spin(spinnerTarget);
			
			var contentShowing = (currentContent == null) ? contents[currentContentIndex] : currentContent;
			
			$.post("db/rate_content_db.php?user_id=<?php echo $user_profile['id']; ?>&content_id=" + contentShowing.content_id + "&calification=" + rating, {
			}, function(response){
				content = contentShowing;
				
				if (rating == 1) {
					document.getElementById('like-button').className  = "button-content-like-active";
					document.getElementById('dislike-button').className  = "button-content-dislike";
					
					content.calification = 1;
				} else if (rating == -1) {
					document.getElementById('like-button').className  = "button-content-like";
					document.getElementById('dislike-button').className  = "button-content-dislike-active";	
					
					content.calification = -1;
				}
				
				spinner.stop();
			});
		}
		
	</script>
	
</head>
<body>

	<div id="fb-root"></div>
	<script>(function(d, s, id) {
	  var js, fjs = d.getElementsByTagName(s)[0];
	  if (d.getElementById(id)) return;
	  js = d.createElement(s); js.id = id;
	  js.src = "//connect.facebook.net/es_LA/all.js";
	  fjs.parentNode.insertBefore(js, fjs);
	}(document, 'script', 'facebook-jssdk'));</script>


    <script>		
	window.fbAsyncInit = function() {
	FB.init({
	  appId : '<?php echo APP_ID;?>',
	  xfbml : true,
	  version : 'v2.0'
	});
	FB.XFBML.parse(document.getElementById('content-like-td'));
	};
	(function(d, s, id){
         var js, fjs = d.getElementsByTagName(s)[0];
         if (d.getElementById(id)) {return;}
         js = d.createElement(s); js.id = id;
         js.src = "//connect.facebook.net/es_LA/sdk.js";
         fjs.parentNode.insertBefore(js, fjs);
       }(document, 'script', 'facebook-jssdk'));
      
	function postFeed() {
		var content_id = (currentContent != null) ? currentContent.content_id : contents[currentContentIndex].content_id;

		FB.ui({
		method: 'share',
		href: '<?php echo APP_CANVAS.CONTENTS_URL; ?>?content_id=' + content_id,
		}, function(response){});
	}
	
	function shareContent() {
		$.post("db/log.php?user_id=<?php echo $user_profile['id']; ?>&activity=Share", {
			}, function(response){ });
		
		postFeed();		
	}
      
	function changeShowingComments() {
		if (showingComments == false) {
			showingComments = true;
			
			document.getElementById("down-options").style.display = 'none';
			document.getElementById("comment-button").className = 'comment-button-active';
			document.getElementById("facebook-comments").style.display = '';
			
			updateComments();
		} else {
			showingComments = false;
			
			document.getElementById("down-options").style.display = '';
			document.getElementById("comment-button").className = 'comment-button';
			document.getElementById("facebook-comments").style.display = 'none';
		}
	}
	
	function updateComments() {
		if (showingComments == true) {
			var contentShowing = (currentContent == null) ? contents[currentContentIndex] : currentContent;
			
			document.getElementById("fb-comments").setAttribute("data-href", APP_CANVAS + "?content_id=" + contentShowing.content_id);

			// Check if FB is loaded
			if ("FB" in window)
			FB.XFBML.parse(document.getElementById('facebook-comments'));
		}
	}
	
	function removeSlashes(str) {
		return str.replace(/\\/g, '');
	}

    </script>


<?php 
$headerFirstOption = SEE_MY_PUBLICATIONS;
$headerSecondOption = CATEGORIES;
$headerThirdOption = PUBLISH;

$headerFirstUrl = PUBLISH_CONTENT."?coming_from=".$current_file;
$headerSecondUrl = CATEGORIES_URL."?coming_from=".$current_file;
$headerThirdUrl = UPLOAD_CONTENT."?coming_from=".$current_file;

$headerFirstClass = "button";
$headerSecondClass = "button-highlighted-green";
$headerThirdClass = "button-highlighted-red";

$bestsHref = "#";
$lastsHref = "#";

$bestsClick = "showBestsContents()";
$lastsClick = "showLastsContents()";

$headerFirstUrl = ($category != "") ? $headerFirstUrl."&category_id=".$category_id : $headerFirstUrl;
$headerSecondUrl = ($category != "") ? $headerSecondUrl."&category_id=".$category_id : $headerSecondUrl;

include_once("header.php"); 
?>

<!-- Slider -->
<div id="slider">
	<div style="font-size: 25px; text-align: center; padding-top: 17px; margin-bottom: 19px;">
		<a id="category-name-upper-slider" style="color: #E8E8E8; text-decoration: none;" href="#">
		<?php 
			$category_name = ($category != "") ? stripslashes($category->name) : "<br />";
			echo $category_name; 	
		?>
		</a>
	</div>
	<div class="shell">
		<div class="slider-holder">
			<div class="slides" style="top: 0px;">			    	
				<!-- Slide -->
			    	<div class="slide-bg">
				    	<table border="0px" class="content-table">
				    		<tr>
				    			<td colspan="6" class="content-td" valign="top">
				    				<span id="content-text" style="display: block; overflow-y: auto; overflow-x: hidden;">
				    					<img src="logo/LoadingLogo.png" style="margin-left: 95px; margin-top: -10px;" />
				    				</span>
				    			</td>
				    		</tr>
				    		<tr>
								<td id="content-author-text" colspan="6" align="right" class="author-current-content"> </td>
				    		</tr>
				    		<tr id="bottom-bar-tr">
				    			<td id="content-like-td" style="display: inline-block; width: 250px"> &nbsp;	</td>
				    			<td width="60px"> <a id="like-button" onclick="rateContent(1)" class="button-content-like" style="visibility: hidden;" href="#">  </a> </td>
				    			<td width="20px"></td>
				    			<td width="60px"> <a id="dislike-button" onclick="rateContent(-1)" class="button-content-dislike" style="visibility: hidden;" href="#"> </a> </td>
				    			<td width="185px"></td>
								<td align="right" valign="bottom"> <a id="comment-button" class="comment-button" onclick="changeShowingComments()" style="visibility: hidden;" href="#">
									<img style="margin-top: 4px;" src="css/images/Speech_Ballon_small.png">
								</a> </td>
								<td width="5px"></td>
								<td align="right" valign="bottom"> <a id="share-button" class="button" onclick="shareContent()" style="visibility: hidden;" href="#"><?php echo SHARE; ?></a> </td>
				    		</tr>
				    	</table>
			    	</div>
			    	<span class="slide-shadow">&nbsp;</span>
			    <!-- End Slide -->			    
			</div>
			
			<!-- Slider Navigation -->
			<div class="slider-nav">
				<a id="prev-button" style="top: 106px;" href="#" onclick="moveLeft();" class="prev">previous</a>
				<a id="next-button" style="top: 106px;" href="#" onclick="moveRight();" class="next">next</a>
			</div>
			<!-- End Slider Navigation -->
		</div>
		
	</div>
</div>
<!-- End Slider -->

<?php include_once('downOptions.php');?>

<div class="support-mail">
	<?php echo SUPPORT_MAIL_TEXT.SUPPORT_MAIL; ?>
</div>

<div id="facebook-comments" class="fb-comments-div" style="display: none;">
	<div id="fb-comments" class="fb-comments" data-href="http://example.com" data-width="700"></div>
</div>

<script> 
	var opts = {
		top: '30%', // Top position relative to parent
		left: '50%' // Left position relative to parent
	};
	var spinnerTarget = document.getElementById('slider');
	var spinner = new Spinner(opts).spin(spinnerTarget);

	showEmptyContents();
	hideMoveArrows();

	showLoadingContent();

	window.onload = function() {
		spinner.stop();
		showContentsSlider();

		// If show specific content
		if (currentContent != null) {
			showingBestContents = null;
			showContent(currentContent);
			showFakeArrows();
		} else {
			// Content loaded from php
			showContentFromList(0);

			if (<?php echo getBests(); ?> == "1") {
				document.getElementById("bests-button").className = 'right-button-active';
				document.getElementById("lasts-button").className = 'left-button';
			} else {
				document.getElementById("bests-button").className = 'right-button';
				document.getElementById("lasts-button").className = 'left-button-active';
			}
		}

		if (contents.length == 0 && currentContent == null) {
			showLastsContents();
		}
	}
</script>

</body>
</html>
